package com.readaloud.wicket;

import java.io.Serializable;


import org.apache.wicket.Component;
import org.apache.wicket.Session;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.markup.html.form.PasswordTextField;
import org.apache.wicket.markup.html.form.TextField;
import org.apache.wicket.markup.html.panel.FeedbackPanel;
import org.apache.wicket.markup.html.panel.Panel;
import org.apache.wicket.model.PropertyModel;
import org.apache.wicket.protocol.http.WebSession;

import com.readaloud.hibernate.user.Author;
import com.readaloud.hibernate.user.Users;

public class UserLoginPanel extends Panel{
	
	public UserLoginPanel(String id){
		super(id);
		FeedbackPanel feedbackPanel = new FeedbackPanel("feedback");
        add(feedbackPanel);
		add(new UserLoginForm("userLoginForm"));
	}

private class UserLoginForm extends Form<Component>{
	private static final long serialVersionUID = -5843190132585293622L;
	private String username;
	private String password;

	
	public UserLoginForm (String id) {
		super(id);
		add(new TextField<String>("username", new PropertyModel<String>(this, "username")));
		add(new PasswordTextField("password", new PropertyModel<String>(this, "password")));
	}

		protected void onSubmit() {
			String userName = getUsername();
			String password = getPassword();
			Users user = WicketApplication.get().getInvertedIndexDao()
					.isValidUser(userName, password);
			if (user != null) {
				
				if ("reader".equals(user.getUserType())) {
					WebSession session = new WebSession(getRequest());
					session.setAttribute("userId", user.getUserId());
					session.setAttribute("userName", user.getUserName());
					setResponsePage(HomePage.class);
				} else if ("author".equals(user.getUserType())) {
					setResponsePage(new AuthorHomePage((Author)user));

				} else {
					info("User id or Password is incorrect!");
				}
			}
		}
	
	
	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
}
}